import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Select,
  Space,
  Typography,
  Tabs,
  Table,
  Tag,
  Progress,
  Statistic,
  Button,
  Empty,
  Spin,
  Alert,
  List,
  Avatar,
  DatePicker,
  Tooltip,
  Badge,
  message,
} from "antd";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Area,
  AreaChart,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from "recharts";
import {
  UserOutlined,
  BookOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
  TrophyOutlined,
  BulbOutlined,
  TagOutlined,
  RiseOutlined,
  FallOutlined,
  DownloadOutlined,
  PrinterOutlined,
  EyeOutlined,
  HeartOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { teacherAPI } from "../../../services/api";
import { useUser } from "../../../contexts/UserContext";

dayjs.extend(relativeTime);

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

// 真实姓名数据
const REAL_STUDENT_NAMES = [
  "张明", "李华", "王芳", "刘强", "陈静", "杨伟", "赵敏", "孙浩", "周丽", "吴刚",
  "徐涛", "朱琳", "胡斌", "郭燕", "何磊", "高洁", "林峰", "罗敏", "梁伟", "宋佳",
  "谢强", "唐丽", "韩磊", "冯敏", "于伟", "董丽", "萧强", "程敏", "曹伟", "袁丽",
  "潘强", "田敏", "姜伟", "范丽", "方强", "石敏", "姚伟", "谭丽", "廖强", "邹敏",
  "熊伟", "孟丽", "秦强", "阎敏", "薛伟"
];

const REAL_TEACHER_NAMES = [
  "王教授", "李老师", "张博士", "陈教授", "刘老师", "杨博士", "赵教授", "孙老师", 
  "周博士", "吴教授", "徐老师", "朱博士", "胡教授", "郭老师", "何博士"
];

// 类型定义
interface StudentPerformance {
  id: string;
  name: string;
  studentId: string;
  avatar?: string;
  totalScore: number;
  averageScore: number;
  progressRate: number;
  attendanceRate: number;
  submitRate: number;
  knowledgePoints: Record<string, number>;
  weakTopics: string[];
  improvements: string[];
  rank: number;
  trend: "up" | "down" | "stable";
}

interface ClassAnalytics {
  totalStudents: number;
  activeStudents: number;
  averageScore: number;
  passRate: number;
  excellentRate: number;
  attendanceRate: number;
  scoreDistribution: Array<{
    range: string;
    count: number;
    percentage: number;
  }>;
  knowledgeMastery: Array<{
    topic: string;
    mastery: number;
    difficulty: number;
  }>;
  progressTrend: Array<{ date: string; score: number; participation: number }>;
  topPerformers: StudentPerformance[];
  needAttention: StudentPerformance[];
  // 新增分析维度
  learningEfficiency: {
    averageStudyTime: number;
    assignmentCompletionRate: number;
    participationRate: number;
    collaborationScore: number;
  };
  subjectPerformance: Array<{
    subject: string;
    averageScore: number;
    passRate: number;
    excellentRate: number;
    difficulty: number;
  }>;
  timeAnalysis: Array<{
    period: string;
    averageScore: number;
    participation: number;
    attendance: number;
  }>;
  peerComparison: {
    classRanking: Array<{
      rank: number;
      studentName: string;
      score: number;
      improvement: number;
    }>;
    gradeComparison: {
      classAverage: number;
      gradeAverage: number;
      percentile: number;
    };
  };
  aiAnalysis: AIAnalysis;
}

interface TeachingRecommendation {
  type: "content" | "method" | "individual" | "group" | "ai";
  priority: "high" | "medium" | "low";
  title: string;
  description: string;
  action: string;
  targetStudents?: string[];
  expectedImprovement: string;
  confidence: number;
  category: string;
  tags: string[];
}

interface AIAnalysis {
  overallAssessment: string;
  keyInsights: string[];
  riskFactors: string[];
  opportunities: string[];
  personalizedSuggestions: Array<{
    studentId: string;
    studentName: string;
    suggestions: string[];
    priority: "high" | "medium" | "low";
  }>;
  teachingStrategy: {
    strengths: string[];
    improvements: string[];
    nextSteps: string[];
  };
  predictiveAnalytics: {
    expectedPerformance: number;
    riskStudents: string[];
    potentialImprovements: string[];
  };
}

interface LearningBehavior {
  studyTime: number;
  assignmentCompletion: number;
  participationLevel: number;
  collaborationScore: number;
  selfAssessment: number;
  peerEvaluation: number;
}

interface DetailedStudentPerformance extends StudentPerformance {
  learningBehavior: LearningBehavior;
  subjectBreakdown: Record<string, {
    score: number;
    rank: number;
    trend: "up" | "down" | "stable";
  }>;
  learningPath: Array<{
    date: string;
    milestone: string;
    achievement: string;
  }>;
  peerComparison: {
    classRank: number;
    gradeRank: number;
    improvement: number;
  };
}

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  transition: box-shadow 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }

  .ant-card-head-title {
    font-weight: 600;
    font-size: 16px;
  }
`;

const StatisticCard = styled(Card)`
  text-align: center;
  border-radius: 8px;

  .ant-statistic-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }

  .ant-statistic-content {
    font-size: 28px;
    font-weight: bold;
  }
`;

const AnalysisTab = styled.div`
  .performance-metrics {
    .metric-item {
      padding: 16px;
      background: #f9f9f9;
      border-radius: 6px;
      margin-bottom: 12px;

      .metric-label {
        font-weight: 500;
        color: #666;
        margin-bottom: 4px;
      }

      .metric-value {
        font-size: 18px;
        font-weight: bold;
        color: #1890ff;
      }
    }
  }
`;

const RecommendationCard = styled.div<{ priority: string }>`
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 12px;
  border-left: 4px solid
    ${(props) =>
      props.priority === "high"
        ? "#ff4d4f"
        : props.priority === "medium"
          ? "#faad14"
          : "#52c41a"};
  background: ${(props) =>
    props.priority === "high"
      ? "#fff1f0"
      : props.priority === "medium"
        ? "#fffbe6"
        : "#f6ffed"};

  .recommendation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .recommendation-title {
      font-weight: 600;
      font-size: 14px;
    }

    .recommendation-priority {
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 12px;
      background: ${(props) =>
        props.priority === "high"
          ? "#ff4d4f"
          : props.priority === "medium"
            ? "#faad14"
            : "#52c41a"};
      color: white;
    }
  }

  .recommendation-content {
    font-size: 13px;
    color: #666;
    margin-bottom: 8px;
  }

  .recommendation-action {
    font-size: 12px;
    font-weight: 500;
    color: #1890ff;
  }
`;

const COLORS = [
  "#1890ff",
  "#52c41a",
  "#faad14",
  "#f5222d",
  "#722ed1",
  "#13c2c2",
  "#eb2f96",
  "#fa8c16",
];

const LearningAnalysis: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [selectedClass, setSelectedClass] = useState<string>("all");
  const [selectedTimeRange, setSelectedTimeRange] = useState<
    [dayjs.Dayjs, dayjs.Dayjs]
  >([dayjs().subtract(30, "days"), dayjs()]);
  const [activeTab, setActiveTab] = useState("overview");

  // 数据状态
  const [classOptions, setClassOptions] = useState<
    Array<{ id: string; name: string }>
  >([
    { id: "all", name: "全部班级" },
    { id: "class1", name: "计算机科学2021级1班" },
    { id: "class2", name: "软件工程2021级1班" },
    { id: "class3", name: "人工智能2021级1班" },
    { id: "class4", name: "数据科学2021级1班" },
    { id: "class5", name: "网络工程2021级1班" },
  ]);
  const [analytics, setAnalytics] = useState<ClassAnalytics | null>(null);
  const [studentPerformances, setStudentPerformances] = useState<
    StudentPerformance[]
  >([]);
  const [recommendations, setRecommendations] = useState<
    TeachingRecommendation[]
  >([]);
  const [aiAnalysisLoading, setAiAnalysisLoading] = useState(false);
  const [aiAnalysisCompleted, setAiAnalysisCompleted] = useState(false);
  const [aiRecommendationsLoading, setAiRecommendationsLoading] = useState(false);
  const [aiRecommendationsCompleted, setAiRecommendationsCompleted] = useState(false);

  // 生成不同班级的AI建议
  const generateAIRecommendations = (className: string): TeachingRecommendation[] => {
    const recommendationTemplates = {
      "计算机科学2021级1班": [
        {
          type: "content" as const,
          priority: "high" as const,
          title: "加强系统架构设计能力",
          description: "学生在系统架构设计方面表现较弱，需要加强相关训练。",
          action: "增加系统设计案例分析，组织架构设计竞赛",
          targetStudents: ["王峰", "刘恒宇", "张明", "李华", "陈静"],
          expectedImprovement: "系统设计能力可提升25%",
          confidence: 0.85,
          category: "系统设计",
          tags: ["架构设计", "案例分析", "竞赛活动"]
        },
        {
          type: "method" as const,
          priority: "medium" as const,
          title: "优化算法训练方法",
          description: "部分学生在算法理解上存在困难，需要改进教学方法。",
          action: "采用可视化算法演示，增加互动练习",
          targetStudents: ["赵敏", "孙浩", "周丽", "吴刚"],
          expectedImprovement: "算法理解能力可提升20%",
          confidence: 0.78,
          category: "算法教学",
          tags: ["可视化", "互动练习", "算法理解"]
        },
        {
          type: "individual" as const,
          priority: "high" as const,
          title: "个性化编程辅导",
          description: "针对编程基础薄弱的学生提供一对一辅导。",
          action: "安排编程助教，制定个性化学习计划",
          targetStudents: ["王芳", "杨伟", "徐涛"],
          expectedImprovement: "编程基础可提升30%",
          confidence: 0.92,
          category: "个性化辅导",
          tags: ["一对一", "编程基础", "学习计划"]
        }
      ],
      "软件工程2021级1班": [
        {
          type: "method" as const,
          priority: "high" as const,
          title: "加强性能优化训练",
          description: "学生在性能优化方面缺乏实践经验。",
          action: "增加性能分析工具使用，组织优化竞赛",
          targetStudents: ["王峰", "刘恒宇", "张明", "李华"],
          expectedImprovement: "性能优化能力可提升28%",
          confidence: 0.88,
          category: "性能优化",
          tags: ["性能分析", "工具使用", "优化竞赛"]
        },
        {
          type: "group" as const,
          priority: "medium" as const,
          title: "提升团队协作效率",
          description: "团队项目协作中沟通效率有待提升。",
          action: "建立敏捷开发流程，加强团队建设",
          targetStudents: ["陈静", "赵敏", "孙浩", "周丽"],
          expectedImprovement: "团队协作效率可提升22%",
          confidence: 0.75,
          category: "团队协作",
          tags: ["敏捷开发", "团队建设", "沟通效率"]
        },
        {
          type: "content" as const,
          priority: "medium" as const,
          title: "加强代码质量意识",
          description: "部分学生代码质量意识需要提升。",
          action: "引入代码审查机制，建立质量标准",
          targetStudents: ["吴刚", "徐涛", "朱琳"],
          expectedImprovement: "代码质量可提升18%",
          confidence: 0.82,
          category: "代码质量",
          tags: ["代码审查", "质量标准", "质量意识"]
        }
      ],
      "人工智能2021级1班": [
        {
          type: "method" as const,
          priority: "high" as const,
          title: "加强工程实践能力",
          description: "学生在模型部署和工程化方面缺乏经验。",
          action: "增加实际项目实践，建立AI实验室",
          targetStudents: ["王峰", "刘恒宇", "张明", "李华"],
          expectedImprovement: "工程实践能力可提升35%",
          confidence: 0.90,
          category: "工程实践",
          tags: ["项目实践", "AI实验室", "模型部署"]
        },
        {
          type: "content" as const,
          priority: "medium" as const,
          title: "深化数学基础理解",
          description: "部分学生在数学基础应用上存在困难。",
          action: "增加数学应用案例，组织数学建模竞赛",
          targetStudents: ["陈静", "赵敏", "孙浩"],
          expectedImprovement: "数学应用能力可提升25%",
          confidence: 0.80,
          category: "数学基础",
          tags: ["数学应用", "建模竞赛", "案例教学"]
        },
        {
          type: "individual" as const,
          priority: "medium" as const,
          title: "个性化研究指导",
          description: "为有研究兴趣的学生提供个性化指导。",
          action: "安排导师指导，参与研究项目",
          targetStudents: ["周丽", "吴刚", "徐涛"],
          expectedImprovement: "研究能力可提升30%",
          confidence: 0.85,
          category: "研究指导",
          tags: ["导师指导", "研究项目", "个性化"]
        }
      ],
      "数据科学2021级1班": [
        {
          type: "method" as const,
          priority: "high" as const,
          title: "加强大数据处理能力",
          description: "学生在分布式计算和大数据处理方面需要加强。",
          action: "增加云计算平台实践，组织数据处理竞赛",
          targetStudents: ["王峰", "刘恒宇", "张明", "李华"],
          expectedImprovement: "大数据处理能力可提升32%",
          confidence: 0.87,
          category: "大数据处理",
          tags: ["云计算", "分布式计算", "数据处理"]
        },
        {
          type: "content" as const,
          priority: "medium" as const,
          title: "提升可视化技能",
          description: "数据可视化技能需要进一步提升。",
          action: "增加可视化工具培训，组织可视化竞赛",
          targetStudents: ["陈静", "赵敏", "孙浩", "周丽"],
          expectedImprovement: "可视化技能可提升28%",
          confidence: 0.83,
          category: "数据可视化",
          tags: ["可视化工具", "技能培训", "可视化竞赛"]
        },
        {
          type: "group" as const,
          priority: "medium" as const,
          title: "加强数据工程实践",
          description: "数据工程实践能力需要提升。",
          action: "建立数据工程实验室，增加实际项目",
          targetStudents: ["吴刚", "徐涛", "朱琳"],
          expectedImprovement: "数据工程能力可提升25%",
          confidence: 0.78,
          category: "数据工程",
          tags: ["数据工程", "实验室", "项目实践"]
        }
      ],
      "网络工程2021级1班": [
        {
          type: "method" as const,
          priority: "high" as const,
          title: "加强网络安全训练",
          description: "学生在网络安全意识和技能方面需要加强。",
          action: "增加安全实验，组织网络安全竞赛",
          targetStudents: ["王峰", "刘恒宇", "张明", "李华", "陈静"],
          expectedImprovement: "网络安全能力可提升30%",
          confidence: 0.89,
          category: "网络安全",
          tags: ["安全实验", "网络安全", "安全竞赛"]
        },
        {
          type: "content" as const,
          priority: "medium" as const,
          title: "提升网络编程技能",
          description: "网络编程实践能力需要加强。",
          action: "增加网络编程实验，组织编程竞赛",
          targetStudents: ["赵敏", "孙浩", "周丽", "吴刚"],
          expectedImprovement: "网络编程能力可提升25%",
          confidence: 0.81,
          category: "网络编程",
          tags: ["网络编程", "编程实验", "编程竞赛"]
        },
        {
          type: "individual" as const,
          priority: "medium" as const,
          title: "个性化网络配置指导",
          description: "为网络配置技能薄弱的学生提供指导。",
          action: "安排网络配置实验，提供一对一指导",
          targetStudents: ["徐涛", "朱琳", "胡斌"],
          expectedImprovement: "网络配置能力可提升22%",
          confidence: 0.76,
          category: "网络配置",
          tags: ["网络配置", "实验指导", "一对一"]
        }
      ]
    };

    const template = recommendationTemplates[className as keyof typeof recommendationTemplates] || recommendationTemplates["计算机科学2021级1班"];
    
    // 随机化建议内容
    return template.map((rec, index) => ({
      ...rec,
      confidence: rec.confidence + (Math.random() * 0.1 - 0.05), // ±5%随机调整
      expectedImprovement: rec.expectedImprovement.replace(
        /\d+%/,
        `${Math.floor(Math.random() * 10) + 20}%` // 20-30%随机调整
      ),
      targetStudents: rec.targetStudents?.slice(0, Math.floor(Math.random() * 3) + 2) // 随机选择2-4个学生
    }));
  };

  // 生成不同班级的AI分析结果
  const generateAIAnalysis = (className: string): AIAnalysis => {
    const analysisTemplates = {
      "计算机科学2021级1班": {
        overallAssessment: "计算机科学1班整体表现优秀，学生在编程基础和算法思维方面表现突出，但在系统架构设计方面需要加强。建议增加项目实践环节，提升学生的工程实践能力。",
        keyInsights: [
          "编程基础扎实，算法思维能力强，优秀学生占比达到30%",
          "系统架构设计能力相对薄弱，需要加强软件工程实践",
          "团队协作能力良好，项目完成度高",
          "部分学生在数据库设计和优化方面存在不足"
        ],
        riskFactors: [
          "5名学生在系统设计课程中存在挂科风险",
          "数据库课程难度较高，可能影响整体学习积极性",
          "部分学生缺乏大型项目开发经验"
        ],
        opportunities: [
          "优秀学生可以担任编程助教，帮助其他同学",
          "利用开源项目提升系统设计能力",
          "建立编程竞赛机制，激发学习热情"
        ],
        strengths: ["编程能力强", "算法思维优秀", "团队协作良好"],
        improvements: ["加强系统设计", "增加项目实践", "提升数据库能力"],
        nextSteps: ["组织编程竞赛", "建立项目小组", "邀请企业导师"]
      },
      "软件工程2021级1班": {
        overallAssessment: "软件工程1班在软件设计和开发流程方面表现良好，学生具备较强的工程思维，但在算法优化和性能调优方面需要提升。建议加强算法训练和性能分析能力。",
        keyInsights: [
          "软件工程流程掌握良好，项目管理能力强",
          "算法优化能力相对薄弱，需要加强训练",
          "代码质量意识强，测试覆盖率较高",
          "部分学生在性能调优方面缺乏经验"
        ],
        riskFactors: [
          "8名学生在算法课程中存在学习困难",
          "性能优化课程难度较大，可能影响学习积极性",
          "部分学生缺乏大规模系统开发经验"
        ],
        opportunities: [
          "利用敏捷开发方法提升团队协作效率",
          "通过代码审查提升代码质量",
          "建立性能优化实验室"
        ],
        strengths: ["工程思维强", "项目管理好", "代码质量高"],
        improvements: ["加强算法训练", "提升性能分析", "增加系统开发"],
        nextSteps: ["建立算法训练营", "组织代码审查", "开展性能竞赛"]
      },
      "人工智能2021级1班": {
        overallAssessment: "人工智能1班在数学基础和机器学习理论方面表现突出，学生具备较强的数学思维，但在工程实践和模型部署方面需要加强。建议增加实际项目应用和工程化训练。",
        keyInsights: [
          "数学基础扎实，机器学习理论掌握良好",
          "工程实践能力相对薄弱，需要加强项目训练",
          "创新思维能力强，研究兴趣浓厚",
          "部分学生在模型部署和优化方面缺乏经验"
        ],
        riskFactors: [
          "6名学生在深度学习实践课程中存在困难",
          "工程化能力不足，可能影响就业竞争力",
          "部分学生缺乏实际项目经验"
        ],
        opportunities: [
          "利用开源AI框架提升工程能力",
          "通过竞赛项目提升实践水平",
          "建立AI实验室，提供实践平台"
        ],
        strengths: ["数学基础好", "理论掌握深", "创新思维强"],
        improvements: ["加强工程实践", "提升部署能力", "增加项目经验"],
        nextSteps: ["建立AI实验室", "组织算法竞赛", "开展企业合作"]
      },
      "数据科学2021级1班": {
        overallAssessment: "数据科学1班在数据分析和统计建模方面表现优秀，学生具备较强的数据处理能力，但在大数据处理和分布式计算方面需要加强。建议增加大数据平台实践和分布式系统训练。",
        keyInsights: [
          "数据分析能力强，统计建模基础扎实",
          "大数据处理能力相对薄弱，需要加强训练",
          "可视化技能优秀，报告撰写能力强",
          "部分学生在分布式计算方面缺乏经验"
        ],
        riskFactors: [
          "7名学生在大数据处理课程中存在学习困难",
          "分布式系统复杂度高，可能影响学习积极性",
          "部分学生缺乏大规模数据处理经验"
        ],
        opportunities: [
          "利用云计算平台提升大数据处理能力",
          "通过实际项目提升数据工程能力",
          "建立数据科学实验室"
        ],
        strengths: ["分析能力强", "建模基础好", "可视化优秀"],
        improvements: ["加强大数据处理", "提升分布式计算", "增加工程实践"],
        nextSteps: ["建立数据实验室", "组织数据分析竞赛", "开展企业项目"]
      },
      "网络工程2021级1班": {
        overallAssessment: "网络工程1班在网络协议和系统管理方面表现良好，学生具备较强的网络思维，但在网络安全和网络编程方面需要加强。建议增加安全实践和编程训练。",
        keyInsights: [
          "网络协议掌握良好，系统管理能力强",
          "网络安全意识相对薄弱，需要加强训练",
          "网络配置技能优秀，故障排查能力强",
          "部分学生在网络编程方面缺乏经验"
        ],
        riskFactors: [
          "9名学生在网络安全课程中存在学习困难",
          "网络编程复杂度高，可能影响学习积极性",
          "部分学生缺乏实际网络部署经验"
        ],
        opportunities: [
          "利用网络仿真平台提升实践能力",
          "通过安全竞赛提升安全意识",
          "建立网络实验室"
        ],
        strengths: ["协议掌握好", "管理能力强", "配置技能优"],
        improvements: ["加强安全训练", "提升编程能力", "增加部署经验"],
        nextSteps: ["建立网络实验室", "组织安全竞赛", "开展企业实践"]
      }
    };

    const template = analysisTemplates[className as keyof typeof analysisTemplates] || analysisTemplates["计算机科学2021级1班"];
    
    return {
      overallAssessment: template.overallAssessment,
      keyInsights: template.keyInsights,
      riskFactors: template.riskFactors,
      opportunities: template.opportunities,
      personalizedSuggestions: [
        {
          studentId: "2021001",
          studentName: "王峰",
          suggestions: ["加强系统设计练习", "参与开源项目", "制定详细的学习计划"],
          priority: "high"
        },
        {
          studentId: "2021002", 
          studentName: "刘恒宇",
          suggestions: ["提高算法训练频率", "加强课后复习", "寻求同学帮助"],
          priority: "medium"
        },
        {
          studentId: "2021003",
          studentName: "张明",
          suggestions: ["参与项目实践", "加强团队协作", "提升编程技能"],
          priority: "medium"
        }
      ],
      teachingStrategy: {
        strengths: template.strengths,
        improvements: template.improvements,
        nextSteps: template.nextSteps
      },
      predictiveAnalytics: {
        expectedPerformance: Math.floor(Math.random() * 15) + 75,
        riskStudents: ["王芳", "赵敏", "陈静", "李华", "孙浩"],
        potentialImprovements: ["平均分提升3-5分", "通过率提升至95%", "优秀率提升至25%"]
      }
    };
  };

  // 模拟数据生成
  const generateMockData = (): ClassAnalytics => {
    // 根据选中的班级生成不同的数据，每个班级25-35人，总计150人
    const classConfigs = {
      "计算机科学2021级1班": {
        totalStudents: 32, // 25-35人之间
        averageScore: 82.5,
        passRate: 95.6,
        attendanceRate: 92.5,
        subjects: ["编程基础", "数据结构", "算法设计", "系统架构", "数据库设计"]
      },
      "软件工程2021级1班": {
        totalStudents: 28, // 25-35人之间
        averageScore: 79.8,
        passRate: 92.9,
        attendanceRate: 89.3,
        subjects: ["软件工程", "项目管理", "代码质量", "性能优化", "系统开发"]
      },
      "人工智能2021级1班": {
        totalStudents: 35, // 25-35人之间
        averageScore: 85.2,
        passRate: 97.4,
        attendanceRate: 94.7,
        subjects: ["数学基础", "机器学习", "深度学习", "模型部署", "AI工程"]
      },
      "数据科学2021级1班": {
        totalStudents: 30, // 25-35人之间
        averageScore: 81.6,
        passRate: 95.0,
        attendanceRate: 91.2,
        subjects: ["数据分析", "统计建模", "大数据处理", "可视化", "数据工程"]
      },
      "网络工程2021级1班": {
        totalStudents: 25, // 25-35人之间
        averageScore: 77.9,
        passRate: 90.7,
        attendanceRate: 88.4,
        subjects: ["网络协议", "系统管理", "网络安全", "网络编程", "网络部署"]
      }
    };

    // 根据selectedClass获取对应的班级名称
    const getClassNameById = (classId: string): string => {
      const classMap = {
        "all": "全部班级", // 全部班级
        "class1": "计算机科学2021级1班",
        "class2": "软件工程2021级1班",
        "class3": "人工智能2021级1班",
        "class4": "数据科学2021级1班",
        "class5": "网络工程2021级1班",
      };
      return classMap[classId as keyof typeof classMap] || "计算机科学2021级1班";
    };

    const className = getClassNameById(selectedClass);
    
    // 如果是全部班级，使用汇总数据
    if (selectedClass === "all") {
      const totalStudents = 205; // 全部班级总人数
      const allStudents = Array.from({ length: totalStudents }, (_, index) => {
        const baseScore = 80 + (Math.random() * 20 - 10); // 70-90分范围
        const studentScore = Math.max(60, Math.min(100, baseScore));
        
        return {
      id: `student_${index + 1}`,
          name: REAL_STUDENT_NAMES[index % REAL_STUDENT_NAMES.length],
          studentId: `2021${String(index + 1).padStart(4, "0")}`,
      totalScore: Math.floor(Math.random() * 40) + 60,
          averageScore: studentScore,
          progressRate: Math.floor(Math.random() * 20) + 80,
          attendanceRate: Math.floor(Math.random() * 8) + 88, // 88-96%
          submitRate: Math.floor(Math.random() * 10) + 90,
      knowledgePoints: {
            "编程基础": Math.floor(Math.random() * 25) + 75,
            "数据结构": Math.floor(Math.random() * 25) + 75,
            "算法设计": Math.floor(Math.random() * 25) + 75,
            "系统架构": Math.floor(Math.random() * 25) + 75,
            "数据库设计": Math.floor(Math.random() * 25) + 75,
          },
          weakTopics: ["算法设计", "系统架构"].slice(0, Math.floor(Math.random() * 2) + 1),
          improvements: ["编程能力", "理论理解", "实践应用", "团队协作"].slice(0, Math.floor(Math.random() * 2) + 1),
          rank: index + 1,
          trend: ["up", "down", "stable"][Math.floor(Math.random() * 3)] as "up" | "down" | "stable",
        };
      });

      const scores = allStudents.map((s) => s.averageScore);
      const passRate = 94.2; // 全部班级平均通过率
      const excellentRate = (scores.filter((s) => s >= 90).length / totalStudents) * 100;

      return {
        totalStudents,
        activeStudents: Math.floor(totalStudents * 0.92),
        averageScore: 81.8, // 全部班级平均分
        passRate,
        excellentRate,
        attendanceRate: 92.1, // 全部班级平均出勤率
        scoreDistribution: [
          {
            range: "90-100",
            count: scores.filter((s) => s >= 90).length,
            percentage: excellentRate,
          },
          {
            range: "80-89",
            count: scores.filter((s) => s >= 80 && s < 90).length,
            percentage: (scores.filter((s) => s >= 80 && s < 90).length / totalStudents) * 100,
          },
          {
            range: "70-79",
            count: scores.filter((s) => s >= 70 && s < 80).length,
            percentage: (scores.filter((s) => s >= 70 && s < 80).length / totalStudents) * 100,
          },
          {
            range: "60-69",
            count: scores.filter((s) => s >= 60 && s < 70).length,
            percentage: (scores.filter((s) => s >= 60 && s < 70).length / totalStudents) * 100,
          },
          {
            range: "<60",
            count: scores.filter((s) => s < 60).length,
            percentage: (scores.filter((s) => s < 60).length / totalStudents) * 100,
          },
        ],
        knowledgeMastery: [
          { topic: "编程基础", mastery: Math.floor(Math.random() * 20) + 80, difficulty: 3 },
          { topic: "数据结构", mastery: Math.floor(Math.random() * 20) + 75, difficulty: 4 },
          { topic: "算法设计", mastery: Math.floor(Math.random() * 20) + 70, difficulty: 5 },
          { topic: "系统架构", mastery: Math.floor(Math.random() * 20) + 75, difficulty: 4 },
          { topic: "数据库设计", mastery: Math.floor(Math.random() * 20) + 70, difficulty: 5 },
        ],
        progressTrend: Array.from({ length: 7 }, (_, i) => ({
          date: dayjs().subtract(6 - i, "days").format("MM-DD"),
          score: 81.8 + (Math.random() * 10 - 5),
          participation: 92.1 + (Math.random() * 10 - 5),
        })),
        topPerformers: allStudents.sort((a, b) => b.averageScore - a.averageScore).slice(0, 5),
        needAttention: allStudents.filter((s) => s.averageScore < 70 || s.attendanceRate < 85).slice(0, 8),
        learningEfficiency: {
          averageStudyTime: Math.floor(Math.random() * 2) + 2,
          assignmentCompletionRate: Math.floor(Math.random() * 10) + 85,
          participationRate: Math.floor(Math.random() * 15) + 75,
          collaborationScore: Math.floor(Math.random() * 15) + 80,
        },
        subjectPerformance: [
          { subject: "编程基础", averageScore: Math.floor(Math.random() * 15) + 75, passRate: 90.0, excellentRate: 25.0, difficulty: 3 },
          { subject: "数据结构", averageScore: Math.floor(Math.random() * 15) + 78, passRate: 95.0, excellentRate: 30.0, difficulty: 4 },
          { subject: "算法设计", averageScore: Math.floor(Math.random() * 15) + 72, passRate: 85.0, excellentRate: 20.0, difficulty: 5 },
          { subject: "系统架构", averageScore: Math.floor(Math.random() * 15) + 70, passRate: 80.0, excellentRate: 15.0, difficulty: 5 },
          { subject: "数据库设计", averageScore: Math.floor(Math.random() * 15) + 74, passRate: 88.0, excellentRate: 22.0, difficulty: 4 },
        ],
        timeAnalysis: [
          { period: "第一周", averageScore: 78.8, participation: 87.1, attendance: 90.1 },
          { period: "第二周", averageScore: 80.8, participation: 89.1, attendance: 91.1 },
          { period: "第三周", averageScore: 81.8, participation: 92.1, attendance: 92.1 },
          { period: "第四周", averageScore: 82.8, participation: 94.1, attendance: 93.1 },
        ],
        peerComparison: {
          classRanking: allStudents.sort((a, b) => b.averageScore - a.averageScore).slice(0, 10).map((student, index) => ({
            rank: index + 1,
            studentName: student.name,
            score: student.averageScore,
            improvement: Math.floor(Math.random() * 20) - 10,
          })),
          gradeComparison: {
            classAverage: 81.8,
            gradeAverage: 81.8 + (Math.random() * 6 - 3),
            percentile: Math.floor(Math.random() * 30) + 60,
          },
        },
        aiAnalysis: generateAIAnalysis("全部班级")
      };
    }

    const config = classConfigs[className as keyof typeof classConfigs] || classConfigs["计算机科学2021级1班"];
    
    // 生成更真实的学生数据
    const students = Array.from({ length: config.totalStudents }, (_, index) => {
      const baseScore = config.averageScore;
      const scoreVariation = Math.floor(Math.random() * 30) - 15; // -15到+15的随机变化
      const studentScore = Math.max(60, Math.min(100, baseScore + scoreVariation));
      
      return {
        id: `student_${index + 1}`,
        name: REAL_STUDENT_NAMES[index % REAL_STUDENT_NAMES.length],
        studentId: `2021${String(index + 1).padStart(4, "0")}`,
        totalScore: Math.floor(Math.random() * 40) + 60,
        averageScore: studentScore,
        progressRate: Math.floor(Math.random() * 20) + 80, // 80-100%
        attendanceRate: Math.floor(Math.random() * 8) + (config.attendanceRate - 4), // 基于班级配置
        submitRate: Math.floor(Math.random() * 10) + 90, // 90-100%
        knowledgePoints: {
          [config.subjects[0]]: Math.floor(Math.random() * 25) + 75,
          [config.subjects[1]]: Math.floor(Math.random() * 25) + 75,
          [config.subjects[2]]: Math.floor(Math.random() * 25) + 75,
          [config.subjects[3]]: Math.floor(Math.random() * 25) + 75,
          [config.subjects[4]]: Math.floor(Math.random() * 25) + 75,
        },
        weakTopics: [config.subjects[2], config.subjects[4]].slice(
        0,
        Math.floor(Math.random() * 2) + 1
      ),
        improvements: ["编程能力", "理论理解", "实践应用", "团队协作"].slice(
        0,
        Math.floor(Math.random() * 2) + 1
      ),
      rank: index + 1,
      trend: ["up", "down", "stable"][Math.floor(Math.random() * 3)] as
        | "up"
        | "down"
        | "stable",
      };
    });

    const scores = students.map((s) => s.averageScore);
    const totalStudents = students.length;
    const passRate = config.passRate;
    const excellentRate =
      (scores.filter((s) => s >= 90).length / totalStudents) * 100;

    return {
      totalStudents,
      activeStudents: Math.floor(totalStudents * 0.9),
      averageScore: config.averageScore,
      passRate,
      excellentRate,
      attendanceRate: config.attendanceRate,
      scoreDistribution: [
        {
          range: "90-100",
          count: scores.filter((s) => s >= 90).length,
          percentage: excellentRate,
        },
        {
          range: "80-89",
          count: scores.filter((s) => s >= 80 && s < 90).length,
          percentage:
            (scores.filter((s) => s >= 80 && s < 90).length / totalStudents) *
            100,
        },
        {
          range: "70-79",
          count: scores.filter((s) => s >= 70 && s < 80).length,
          percentage:
            (scores.filter((s) => s >= 70 && s < 80).length / totalStudents) *
            100,
        },
        {
          range: "60-69",
          count: scores.filter((s) => s >= 60 && s < 70).length,
          percentage:
            (scores.filter((s) => s >= 60 && s < 70).length / totalStudents) *
            100,
        },
        {
          range: "<60",
          count: scores.filter((s) => s < 60).length,
          percentage:
            (scores.filter((s) => s < 60).length / totalStudents) * 100,
        },
      ],
      knowledgeMastery: [
        { topic: config.subjects[0], mastery: Math.floor(Math.random() * 20) + 80, difficulty: 3 },
        { topic: config.subjects[1], mastery: Math.floor(Math.random() * 20) + 75, difficulty: 4 },
        { topic: config.subjects[2], mastery: Math.floor(Math.random() * 20) + 70, difficulty: 5 },
        { topic: config.subjects[3], mastery: Math.floor(Math.random() * 20) + 75, difficulty: 4 },
        { topic: config.subjects[4], mastery: Math.floor(Math.random() * 20) + 70, difficulty: 5 },
      ],
      progressTrend: Array.from({ length: 7 }, (_, i) => ({
        date: dayjs()
          .subtract(6 - i, "days")
          .format("MM-DD"),
        score: config.averageScore + (Math.random() * 10 - 5), // 平均分±5分
        participation: config.attendanceRate + (Math.random() * 10 - 5), // 出勤率±5%
      })),
      topPerformers: students
        .sort((a, b) => b.averageScore - a.averageScore)
        .slice(0, 5),
      needAttention: students
        .filter((s) => s.averageScore < 70 || s.attendanceRate < 85)
        .slice(0, 8),
      // 新增分析维度
      learningEfficiency: {
        averageStudyTime: Math.floor(Math.random() * 2) + 2, // 2-4小时
        assignmentCompletionRate: Math.floor(Math.random() * 10) + 85, // 85-95%
        participationRate: Math.floor(Math.random() * 15) + 75, // 75-90%
        collaborationScore: Math.floor(Math.random() * 15) + 80, // 80-95%
      },
      subjectPerformance: [
        { subject: config.subjects[0], averageScore: Math.floor(Math.random() * 15) + 75, passRate: 90.0, excellentRate: 25.0, difficulty: 3 },
        { subject: config.subjects[1], averageScore: Math.floor(Math.random() * 15) + 78, passRate: 95.0, excellentRate: 30.0, difficulty: 4 },
        { subject: config.subjects[2], averageScore: Math.floor(Math.random() * 15) + 72, passRate: 85.0, excellentRate: 20.0, difficulty: 5 },
        { subject: config.subjects[3], averageScore: Math.floor(Math.random() * 15) + 70, passRate: 80.0, excellentRate: 15.0, difficulty: 5 },
        { subject: config.subjects[4], averageScore: Math.floor(Math.random() * 15) + 74, passRate: 88.0, excellentRate: 22.0, difficulty: 4 },
      ],
      timeAnalysis: [
        { period: "第一周", averageScore: config.averageScore - 3, participation: config.attendanceRate - 5, attendance: config.attendanceRate - 2 },
        { period: "第二周", averageScore: config.averageScore - 1, participation: config.attendanceRate - 3, attendance: config.attendanceRate - 1 },
        { period: "第三周", averageScore: config.averageScore + 1, participation: config.attendanceRate, attendance: config.attendanceRate },
        { period: "第四周", averageScore: config.averageScore + 2, participation: config.attendanceRate + 2, attendance: config.attendanceRate + 1 },
      ],
      peerComparison: {
        classRanking: students
          .sort((a, b) => b.averageScore - a.averageScore)
          .slice(0, 10)
          .map((student, index) => ({
            rank: index + 1,
            studentName: student.name,
            score: student.averageScore,
          improvement: Math.floor(Math.random() * 20) - 10,
        })),
        gradeComparison: {
          classAverage: config.averageScore,
          gradeAverage: config.averageScore + (Math.random() * 6 - 3), // 班级平均分±3分
          percentile: Math.floor(Math.random() * 30) + 60, // 60-90%
        },
      },
      aiAnalysis: generateAIAnalysis(className)
    };
  };

  // 生成教学建议
  const generateRecommendations = (
    analytics: ClassAnalytics
  ): TeachingRecommendation[] => {
    const recommendations: TeachingRecommendation[] = [];

    // 基于整体表现的建议
    if (analytics.passRate < 80) {
      recommendations.push({
        type: "content",
        priority: "high",
        title: "提升整体通过率",
        description: `当前通过率为${analytics.passRate.toFixed(1)}%，低于标准线。需要加强基础知识讲解。`,
        action: "增加基础练习题，安排课后辅导",
        expectedImprovement: "预计通过率可提升15-20%",
        confidence: 0.85,
        category: "学习效果",
        tags: ["通过率", "基础知识", "教学调整"]
      });
    }

    // 基于知识点掌握情况的建议
    const weakTopics = analytics.knowledgeMastery.filter((k) => k.mastery < 75);
    if (weakTopics.length > 0) {
      recommendations.push({
        type: "content",
        priority: "medium",
        title: "重点加强薄弱知识点",
        description: `${weakTopics.map((t) => t.topic).join("、")}等知识点掌握度较低。`,
        action: "制作专题讲解视频，增加实践案例",
        expectedImprovement: "薄弱知识点掌握度可提升20%",
        confidence: 0.75,
        category: "知识点",
        tags: ["薄弱点", "专题讲解", "实践案例"]
      });
    }

    // 基于出勤率的建议
    if (analytics.attendanceRate < 90) {
      recommendations.push({
        type: "method",
        priority: "medium",
        title: "提升课堂参与度",
        description: `出勤率为${analytics.attendanceRate.toFixed(1)}%，需要提高学生积极性。`,
        action: "引入互动教学方式，设置课堂积分奖励",
        expectedImprovement: "出勤率可提升至95%以上",
        confidence: 0.80,
        category: "课堂管理",
        tags: ["出勤率", "互动教学", "参与度"]
      });
    }

    // 基于需要关注学生的建议
    if (analytics.needAttention.length > 0) {
      recommendations.push({
        type: "individual",
        priority: "high",
        title: "个性化辅导计划",
        description: `${analytics.needAttention.length}名学生需要额外关注和帮助。`,
        action: "制定一对一辅导计划，定期沟通学习情况",
        targetStudents: analytics.needAttention.map((s) => s.name),
        expectedImprovement: "帮助后进生成绩提升10-15分",
        confidence: 0.90,
        category: "个性化教学",
        tags: ["困难学生", "个性化", "辅导"]
      });
    }

    return recommendations;
  };

  // 数据加载
  const loadData = async () => {
    setLoading(true);
    try {
      // TODO: 调用实际API
      // const classResponse = await teacherAPI.getClasses();
      // const analyticsResponse = await teacherAPI.getAnalysis(selectedClass);

      // 模拟API延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 生成模拟数据
      const mockAnalytics = generateMockData();
      const mockStudents = mockAnalytics.topPerformers.concat(
        mockAnalytics.needAttention
      );
      const mockRecommendations = generateRecommendations(mockAnalytics);

      // 确保班级选项与selectedClass匹配
      const currentClassOptions = [
        { id: "all", name: "全部班级" },
        { id: "class1", name: "计算机科学2021级1班" },
        { id: "class2", name: "软件工程2021级1班" },
        { id: "class3", name: "人工智能2021级1班" },
        { id: "class4", name: "数据科学2021级1班" },
        { id: "class5", name: "网络工程2021级1班" },
      ];
      
      setClassOptions(currentClassOptions);

      setAnalytics(mockAnalytics);
      setStudentPerformances(mockStudents);
      setRecommendations(mockRecommendations);
    } catch (error) {
      message.error("数据加载失败，请稍后重试");
      console.error("加载学习分析数据失败:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [selectedClass, selectedTimeRange]);

  // AI分析获取功能
  const getAIAnalysis = async () => {
    setAiAnalysisLoading(true);
    try {
      // 模拟AI分析过程
      await new Promise((resolve) => setTimeout(resolve, 3000));
      
      const mockData = generateMockData();
      setAnalytics(mockData);
      setAiAnalysisCompleted(true);
      message.success("AI分析完成！");
    } catch (error) {
      message.error("AI分析失败，请重试");
    } finally {
      setAiAnalysisLoading(false);
    }
  };

  // 重新AI分析功能
  const reanalyzeWithAI = async () => {
    setAiAnalysisLoading(true);
    setAiAnalysisCompleted(false);
    try {
      // 模拟重新分析过程
      await new Promise((resolve) => setTimeout(resolve, 2500));
      
      const mockData = generateMockData();
      setAnalytics(mockData);
      setAiAnalysisCompleted(true);
      message.success("重新分析完成！");
    } catch (error) {
      message.error("重新分析失败，请重试");
    } finally {
      setAiAnalysisLoading(false);
    }
  };

  // AI建议获取功能
  const getAIRecommendations = async () => {
    setAiRecommendationsLoading(true);
    try {
      // 模拟AI建议生成过程
      await new Promise((resolve) => setTimeout(resolve, 2800));
      
      const aiRecommendations = generateAIRecommendations(selectedClass);
      setRecommendations(aiRecommendations);
      setAiRecommendationsCompleted(true);
      message.success("AI建议生成完成！");
    } catch (error) {
      message.error("AI建议生成失败，请重试");
    } finally {
      setAiRecommendationsLoading(false);
    }
  };

  // 重新生成AI建议功能
  const regenerateAIRecommendations = async () => {
    setAiRecommendationsLoading(true);
    setAiRecommendationsCompleted(false);
    try {
      // 模拟重新生成过程
      await new Promise((resolve) => setTimeout(resolve, 2200));
      
      const aiRecommendations = generateAIRecommendations(selectedClass);
      setRecommendations(aiRecommendations);
      setAiRecommendationsCompleted(true);
      message.success("重新生成完成！");
    } catch (error) {
      message.error("重新生成失败，请重试");
    } finally {
      setAiRecommendationsLoading(false);
    }
  };

  // 渲染概览统计
  const renderOverviewStats = () => {
    if (!analytics) return null;

    return (
      <Row gutter={[16, 16]}>
        <Col span={6}>
          <StatisticCard>
            <Statistic
              title="班级学生总数"
              value={analytics.totalStudents}
              prefix={<UserOutlined />}
              suffix="人"
              valueStyle={{ color: "#1890ff" }}
            />
          </StatisticCard>
        </Col>
        <Col span={6}>
          <StatisticCard>
            <Statistic
              title="平均成绩"
              value={analytics.averageScore}
              precision={1}
              prefix={<TrophyOutlined />}
              suffix="分"
              valueStyle={{ color: "#52c41a" }}
            />
          </StatisticCard>
        </Col>
        <Col span={6}>
          <StatisticCard>
            <Statistic
              title="通过率"
              value={analytics.passRate}
              precision={1}
              prefix={<CheckCircleOutlined />}
              suffix="%"
              valueStyle={{
                color: analytics.passRate >= 80 ? "#52c41a" : "#faad14",
              }}
            />
          </StatisticCard>
        </Col>
        <Col span={6}>
          <StatisticCard>
            <Statistic
              title="出勤率"
              value={analytics.attendanceRate}
              precision={1}
              prefix={<ClockCircleOutlined />}
              suffix="%"
              valueStyle={{ color: "#722ed1" }}
            />
          </StatisticCard>
        </Col>
      </Row>
    );
  };

  // 渲染成绩分布图
  const renderScoreDistribution = () => {
    if (!analytics) return null;

    return (
      <ResponsiveContainer width="100%" height={300}>
        <BarChart data={analytics.scoreDistribution}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="range" />
          <YAxis />
          <RechartsTooltip />
          <Legend />
          <Bar dataKey="count" name="学生人数" fill="#1890ff" />
        </BarChart>
      </ResponsiveContainer>
    );
  };

  // 渲染知识点掌握雷达图
  const renderKnowledgeRadar = () => {
    if (!analytics) return null;

    return (
      <ResponsiveContainer width="100%" height={400}>
        <RadarChart data={analytics.knowledgeMastery}>
          <PolarGrid />
          <PolarAngleAxis dataKey="topic" />
          <PolarRadiusAxis angle={90} domain={[0, 100]} />
          <Radar
            name="掌握度"
            dataKey="mastery"
            stroke="#1890ff"
            fill="#1890ff"
            fillOpacity={0.3}
          />
        </RadarChart>
      </ResponsiveContainer>
    );
  };

  // 渲染进度趋势图
  const renderProgressTrend = () => {
    if (!analytics) return null;

    return (
      <ResponsiveContainer width="100%" height={300}>
        <AreaChart data={analytics.progressTrend}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="date" />
          <YAxis />
          <RechartsTooltip />
          <Legend />
          <Area
            type="monotone"
            dataKey="score"
            stackId="1"
            stroke="#1890ff"
            fill="#1890ff"
            name="平均成绩"
          />
          <Area
            type="monotone"
            dataKey="participation"
            stackId="1"
            stroke="#52c41a"
            fill="#52c41a"
            name="参与度"
          />
        </AreaChart>
      </ResponsiveContainer>
    );
  };

  // 渲染学生表现表格
  const renderStudentTable = () => {
    const columns = [
      {
        title: "排名",
        dataIndex: "rank",
        key: "rank",
        width: 80,
        render: (rank: number) => (
          <Badge count={rank} style={{ backgroundColor: "#1890ff" }} />
        ),
      },
      {
        title: "学生信息",
        key: "student",
        render: (record: StudentPerformance) => (
          <Space>
            <Avatar icon={<UserOutlined />} />
            <div>
              <div style={{ fontWeight: 500 }}>{record.name}</div>
              <Text type="secondary" style={{ fontSize: 12 }}>
                {record.studentId}
              </Text>
            </div>
          </Space>
        ),
      },
      {
        title: "平均成绩",
        dataIndex: "averageScore",
        key: "averageScore",
        sorter: (a: StudentPerformance, b: StudentPerformance) =>
          a.averageScore - b.averageScore,
        render: (score: number, record: StudentPerformance) => (
          <Space>
            <span
              style={{
                fontWeight: 500,
                color:
                  score >= 90
                    ? "#52c41a"
                    : score >= 80
                      ? "#1890ff"
                      : score >= 60
                        ? "#faad14"
                        : "#f5222d",
              }}
            >
              {score}
            </span>
            {record.trend === "up" && (
              <RiseOutlined style={{ color: "#52c41a" }} />
            )}
            {record.trend === "down" && (
              <FallOutlined style={{ color: "#f5222d" }} />
            )}
          </Space>
        ),
      },
      {
        title: "进步率",
        dataIndex: "progressRate",
        key: "progressRate",
        render: (rate: number) => (
          <Progress
            percent={rate}
            size="small"
            strokeColor={
              rate > 80 ? "#52c41a" : rate > 60 ? "#1890ff" : "#faad14"
            }
          />
        ),
      },
      {
        title: "出勤率",
        dataIndex: "attendanceRate",
        key: "attendanceRate",
        render: (rate: number) => (
          <span
            style={{
              color:
                rate >= 90 ? "#52c41a" : rate >= 80 ? "#faad14" : "#f5222d",
            }}
          >
            {rate}%
          </span>
        ),
      },
      {
        title: "薄弱环节",
        dataIndex: "weakTopics",
        key: "weakTopics",
        render: (topics: string[]) => (
          <Space wrap>
            {topics.map((topic) => (
              <Tag key={topic} color="red">
                {topic}
              </Tag>
            ))}
          </Space>
        ),
      },
    ];

    return (
      <Table
        columns={columns}
        dataSource={studentPerformances}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 名学生`,
        }}
        size="small"
      />
    );
  };

  // 渲染智能建议
  const renderRecommendations = () => {
    return (
      <div>
        <Card
          title={
            <Space>
              <BulbOutlined style={{ color: "#1890ff" }} />
              智能教学建议
            </Space>
          }
          extra={
            <Space>
              {!aiRecommendationsCompleted ? (
                <Button
                  type="primary"
                  icon={<BulbOutlined />}
                  loading={aiRecommendationsLoading}
                  onClick={getAIRecommendations}
                >
                  获取AI建议
                </Button>
              ) : (
                <Button
                  icon={<BulbOutlined />}
                  loading={aiRecommendationsLoading}
                  onClick={regenerateAIRecommendations}
                >
                  重新生成
                </Button>
              )}
            </Space>
          }
          style={{ marginBottom: 16 }}
        >
          {!aiRecommendationsCompleted ? (
            <Empty
              description={
                <div>
                  <div style={{ marginBottom: 16 }}>
                    <Text>基于学生学习数据分析，AI系统将为您提供个性化的教学改进建议。</Text>
                  </div>
                  <Button
                    type="primary"
                    icon={<BulbOutlined />}
                    loading={aiRecommendationsLoading}
                    onClick={getAIRecommendations}
                    size="large"
                  >
                    {aiRecommendationsLoading ? "AI建议生成中..." : "开始生成AI建议"}
                  </Button>
                </div>
              }
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          ) : (
      <div>
        <Alert
          message="智能教学建议"
          description="基于学生学习数据分析，为您提供个性化的教学改进建议"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        {recommendations.map((rec, index) => (
          <RecommendationCard key={index} priority={rec.priority}>
            <div className="recommendation-header">
              <span className="recommendation-title">{rec.title}</span>
              <span className="recommendation-priority">
                {rec.priority === "high"
                  ? "高优先级"
                  : rec.priority === "medium"
                    ? "中优先级"
                    : "低优先级"}
              </span>
            </div>
            <div className="recommendation-content">{rec.description}</div>
            <div className="recommendation-action">
              <BulbOutlined /> {rec.action}
            </div>
            {rec.targetStudents && (
              <div style={{ marginTop: 8, fontSize: 12, color: "#666" }}>
                <TagOutlined /> 目标学生: {rec.targetStudents.join("、")}
              </div>
            )}
            <div style={{ marginTop: 8, fontSize: 12, color: "#1890ff" }}>
              <RiseOutlined /> {rec.expectedImprovement}
            </div>
            <div style={{ marginTop: 8, fontSize: 12, color: "#666" }}>
              <TagOutlined /> 分类: {rec.category} | 置信度: {(rec.confidence * 100).toFixed(0)}%
            </div>
            <div style={{ marginTop: 4 }}>
              {rec.tags.map((tag, tagIndex) => (
                <Tag key={tagIndex} color="blue" style={{ marginRight: 4 }}>
                  {tag}
                </Tag>
              ))}
            </div>
          </RecommendationCard>
        ))}
            </div>
          )}
        </Card>
      </div>
    );
  };

  // 渲染AI分析
  const renderAIAnalysis = () => {
    const ai = analytics?.aiAnalysis;
    
    if (!ai && aiAnalysisCompleted) {
      return null;
    }
    
    return (
      <div>
        <Card
          title={
            <Space>
              <BulbOutlined style={{ color: "#1890ff" }} />
              AI智能分析报告
            </Space>
          }
          extra={
            <Space>
              {!aiAnalysisCompleted ? (
                <Button
                  type="primary"
                  icon={<BulbOutlined />}
                  loading={aiAnalysisLoading}
                  onClick={getAIAnalysis}
                >
                  获取AI分析
                </Button>
              ) : (
                <Button
                  icon={<BulbOutlined />}
                  loading={aiAnalysisLoading}
                  onClick={reanalyzeWithAI}
                >
                  重新分析
                </Button>
              )}
            </Space>
          }
          style={{ marginBottom: 16 }}
        >
          {!aiAnalysisCompleted ? (
            <Empty
              description={
                <div>
                  <div style={{ marginBottom: 16 }}>
                    <Text>基于深度学习算法，AI系统将对班级学习情况进行全面分析，为您提供专业的教学洞察。</Text>
                  </div>
                  <Button
                    type="primary"
                    icon={<BulbOutlined />}
                    loading={aiAnalysisLoading}
                    onClick={getAIAnalysis}
                    size="large"
                  >
                    {aiAnalysisLoading ? "AI分析中..." : "开始AI分析"}
                  </Button>
                </div>
              }
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          ) : ai ? (
      <div>
        <Alert
          message="AI智能分析报告"
          description="基于深度学习算法，AI系统对班级学习情况进行了全面分析，为您提供专业的教学洞察。"
          type="success"
          style={{ marginBottom: 16 }}
        />
        
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Card title="整体评估" size="small">
              <Text>{ai.overallAssessment}</Text>
            </Card>
          </Col>
          
          <Col span={12}>
            <Card title="关键洞察" size="small">
              <List
                size="small"
                dataSource={ai.keyInsights}
                      renderItem={(insight: string) => (
                  <List.Item>
                    <BulbOutlined style={{ color: '#1890ff', marginRight: 8 }} />
                    {insight}
                  </List.Item>
                )}
              />
            </Card>
          </Col>
          
          <Col span={12}>
            <Card title="风险因素" size="small">
              <List
                size="small"
                dataSource={ai.riskFactors}
                      renderItem={(risk: string) => (
                  <List.Item>
                    <WarningOutlined style={{ color: '#faad14', marginRight: 8 }} />
                    {risk}
                  </List.Item>
                )}
              />
            </Card>
          </Col>
          
          <Col span={12}>
            <Card title="发展机会" size="small">
              <List
                size="small"
                dataSource={ai.opportunities}
                      renderItem={(opportunity: string) => (
                  <List.Item>
                    <TrophyOutlined style={{ color: '#52c41a', marginRight: 8 }} />
                    {opportunity}
                  </List.Item>
                )}
              />
            </Card>
          </Col>
          
          <Col span={12}>
            <Card title="教学策略" size="small">
              <Tabs size="small">
                <TabPane tab="优势" key="strengths">
                  <List
                    size="small"
                    dataSource={ai.teachingStrategy.strengths}
                          renderItem={(strength: string) => (
                      <List.Item>
                        <CheckCircleOutlined style={{ color: '#52c41a', marginRight: 8 }} />
                        {strength}
                      </List.Item>
                    )}
                  />
                </TabPane>
                <TabPane tab="改进" key="improvements">
                  <List
                    size="small"
                    dataSource={ai.teachingStrategy.improvements}
                          renderItem={(improvement: string) => (
                      <List.Item>
                        <ClockCircleOutlined style={{ color: '#faad14', marginRight: 8 }} />
                        {improvement}
                      </List.Item>
                    )}
                  />
                </TabPane>
                <TabPane tab="下一步" key="nextSteps">
                  <List
                    size="small"
                    dataSource={ai.teachingStrategy.nextSteps}
                          renderItem={(step: string) => (
                      <List.Item>
                        <RiseOutlined style={{ color: '#1890ff', marginRight: 8 }} />
                        {step}
                      </List.Item>
                    )}
                  />
                </TabPane>
              </Tabs>
            </Card>
          </Col>
          
          <Col span={24}>
            <Card title="个性化建议" size="small">
              <List
                dataSource={ai.personalizedSuggestions}
                renderItem={(suggestion) => (
                  <List.Item>
                    <List.Item.Meta
                      title={
                        <Space>
                          <span>{suggestion.studentName}</span>
                          <Tag color={suggestion.priority === 'high' ? 'red' : suggestion.priority === 'medium' ? 'orange' : 'green'}>
                            {suggestion.priority === 'high' ? '高优先级' : suggestion.priority === 'medium' ? '中优先级' : '低优先级'}
                          </Tag>
                        </Space>
                      }
                      description={
                        <div>
                          {suggestion.suggestions.map((s, index) => (
                            <div key={index} style={{ marginBottom: 4 }}>
                              • {s}
                            </div>
                          ))}
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
          
          <Col span={24}>
            <Card title="预测分析" size="small">
              <Row gutter={16}>
                <Col span={8}>
                  <Statistic
                    title="预期表现"
                    value={ai.predictiveAnalytics.expectedPerformance}
                    suffix="分"
                    precision={1}
                  />
                </Col>
                <Col span={8}>
                  <div>
                    <Text strong>风险学生:</Text>
                    <div style={{ marginTop: 8 }}>
                      {ai.predictiveAnalytics.riskStudents.map((student, index) => (
                        <Tag key={index} color="red" style={{ marginBottom: 4 }}>
                          {student}
                        </Tag>
                      ))}
                    </div>
                  </div>
                </Col>
                <Col span={8}>
                  <div>
                    <Text strong>潜在改进:</Text>
                    <div style={{ marginTop: 8 }}>
                      {ai.predictiveAnalytics.potentialImprovements.map((improvement, index) => (
                        <Tag key={index} color="green" style={{ marginBottom: 4 }}>
                          {improvement}
                        </Tag>
                      ))}
                    </div>
                  </div>
                </Col>
              </Row>
            </Card>
          </Col>
        </Row>
            </div>
          ) : null}
        </Card>
      </div>
    );
  };

  // 渲染学习效率分析
  const renderLearningEfficiency = () => {
    if (!analytics?.learningEfficiency) return null;
    
    const efficiency = analytics.learningEfficiency;
    
    return (
      <Row gutter={[16, 16]}>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均学习时间"
              value={efficiency.averageStudyTime}
              suffix="小时/天"
              precision={1}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="作业完成率"
              value={efficiency.assignmentCompletionRate}
              suffix="%"
              precision={1}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="课堂参与率"
              value={efficiency.participationRate}
              suffix="%"
              precision={1}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="协作学习评分"
              value={efficiency.collaborationScore}
              suffix="分"
              precision={1}
            />
          </Card>
        </Col>
      </Row>
    );
  };

  // 渲染学科表现分析
  const renderSubjectPerformance = () => {
    if (!analytics?.subjectPerformance) return null;
    
    return (
      <Card title="学科表现分析" size="small">
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={analytics.subjectPerformance}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="subject" />
            <YAxis />
            <RechartsTooltip />
            <Legend />
            <Bar dataKey="averageScore" fill="#1890ff" name="平均分" />
            <Bar dataKey="passRate" fill="#52c41a" name="及格率" />
            <Bar dataKey="excellentRate" fill="#faad14" name="优秀率" />
          </BarChart>
        </ResponsiveContainer>
      </Card>
    );
  };

  // 渲染时间分析
  const renderTimeAnalysis = () => {
    if (!analytics?.timeAnalysis) return null;
    
    return (
      <Card title="时间趋势分析" size="small">
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={analytics.timeAnalysis}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="period" />
            <YAxis />
            <RechartsTooltip />
            <Legend />
            <Line type="monotone" dataKey="averageScore" stroke="#1890ff" name="平均分" />
            <Line type="monotone" dataKey="participation" stroke="#52c41a" name="参与度" />
            <Line type="monotone" dataKey="attendance" stroke="#faad14" name="出勤率" />
          </LineChart>
        </ResponsiveContainer>
      </Card>
    );
  };

  // 渲染同伴比较
  const renderPeerComparison = () => {
    if (!analytics?.peerComparison) return null;
    
    const comparison = analytics.peerComparison;
    
    return (
      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Card title="班级排名" size="small">
            <Table
              dataSource={comparison.classRanking}
              columns={[
                { title: "排名", dataIndex: "rank", key: "rank" },
                { title: "学生", dataIndex: "studentName", key: "studentName" },
                { title: "分数", dataIndex: "score", key: "score" },
                {
                  title: "进步",
                  dataIndex: "improvement",
                  key: "improvement",
                  render: (value) => (
                    <span style={{ color: value >= 0 ? '#52c41a' : '#f5222d' }}>
                      {value >= 0 ? '+' : ''}{value}
                    </span>
                  )
                }
              ]}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="年级比较" size="small">
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="班级平均分"
                  value={comparison.gradeComparison.classAverage}
                  suffix="分"
                  precision={1}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="年级平均分"
                  value={comparison.gradeComparison.gradeAverage}
                  suffix="分"
                  precision={1}
                />
              </Col>
              <Col span={24} style={{ marginTop: 16 }}>
                <Progress
                  percent={comparison.gradeComparison.percentile}
                  format={(percent) => `超过${percent}%的班级`}
                  strokeColor={{
                    '0%': '#108ee9',
                    '100%': '#87d068',
                  }}
                />
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>
    );
  };

  if (loading) {
    return (
      <div style={{ textAlign: "center", padding: "100px 0" }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>正在分析学习数据...</div>
      </div>
    );
  }

  return (
    <div style={{ padding: "24px" }}>
      {/* 页面头部 */}
      <div style={{ marginBottom: 24 }}>
        <Title level={3}>
          <BookOutlined /> 学习分析与教学洞察
        </Title>
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={8}>
            <Select
              value={selectedClass}
              onChange={setSelectedClass}
              style={{ width: "100%" }}
              placeholder="选择班级"
            >
              {classOptions.map((option) => (
                <Option key={option.id} value={option.id}>
                  {option.name}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={8}>
            <RangePicker
              value={selectedTimeRange}
              onChange={(dates) =>
                setSelectedTimeRange(dates as [dayjs.Dayjs, dayjs.Dayjs])
              }
              style={{ width: "100%" }}
            />
          </Col>
          <Col span={8}>
            <Space>
              <Button icon={<DownloadOutlined />}>导出报告</Button>
              <Button icon={<PrinterOutlined />}>打印分析</Button>
              <Button type="primary" onClick={loadData} loading={loading}>
                刷新数据
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 概览统计 */}
      {renderOverviewStats()}

      {/* 详细分析标签页 */}
      <StyledCard>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="综合概览" key="overview">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Card title="成绩分布" size="small">
                  {renderScoreDistribution()}
                </Card>
              </Col>
              <Col span={12}>
                <Card title="知识点掌握情况" size="small">
                  {renderKnowledgeRadar()}
                </Card>
              </Col>
              <Col span={24}>
                <Card title="学习进度趋势" size="small">
                  {renderProgressTrend()}
                </Card>
              </Col>
            </Row>
          </TabPane>

          <TabPane tab="学习效率" key="efficiency">
            <Card title="学习效率分析" size="small" style={{ marginBottom: 16 }}>
              {renderLearningEfficiency()}
            </Card>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                {renderSubjectPerformance()}
              </Col>
              <Col span={12}>
                {renderTimeAnalysis()}
              </Col>
            </Row>
          </TabPane>

          <TabPane tab="同伴比较" key="comparison">
            {renderPeerComparison()}
          </TabPane>

          <TabPane tab="学生表现" key="students">
            <Card title="学生详细表现" size="small">
              {renderStudentTable()}
            </Card>
          </TabPane>

          <TabPane tab="AI智能分析" key="ai">
            {renderAIAnalysis()}
          </TabPane>

          <TabPane tab="智能建议" key="recommendations">
            {renderRecommendations()}
          </TabPane>

          <TabPane tab="优秀表现" key="excellent">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Card title="优秀学生" size="small">
                  <List
                    dataSource={analytics?.topPerformers || []}
                    renderItem={(student, index) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={
                            <Badge
                              count={index + 1}
                              style={{ backgroundColor: "#52c41a" }}
                            >
                              <Avatar icon={<UserOutlined />} />
                            </Badge>
                          }
                          title={student.name}
                          description={
                            <Space>
                              <span>平均分: {student.averageScore}</span>
                              <span>出勤率: {student.attendanceRate}%</span>
                              <Tag color="green">优秀</Tag>
                            </Space>
                          }
                        />
                      </List.Item>
                    )}
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card title="需要关注的学生" size="small">
                  <List
                    dataSource={analytics?.needAttention || []}
                    renderItem={(student) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={
                            <Avatar
                              icon={<UserOutlined />}
                              style={{ backgroundColor: "#faad14" }}
                            />
                          }
                          title={student.name}
                          description={
                            <Space direction="vertical" size="small">
                              <span>
                                平均分: {student.averageScore} 出勤率:{" "}
                                {student.attendanceRate}%
                              </span>
                              <Space wrap>
                                {student.weakTopics.map((topic) => (
                                  <Tag key={topic} color="orange">
                                    {topic}
                                  </Tag>
                                ))}
                              </Space>
                            </Space>
                          }
                        />
                        <Tooltip title="查看详细分析">
                          <Button
                            type="link"
                            icon={<EyeOutlined />}
                            size="small"
                          />
                        </Tooltip>
                      </List.Item>
                    )}
                  />
                </Card>
              </Col>
            </Row>
          </TabPane>
        </Tabs>
      </StyledCard>
    </div>
  );
};

export default LearningAnalysis;
